from flask import (Blueprint, request, session)
from flaskr import Utils
from flaskr.server.SheetsServer import *

import os
bp = Blueprint('clearCache', __name__, url_prefix='/clearCache')

@bp.route('', methods = ['POST'])
def ClearCache():
    now_path = os.path.abspath(os.path.dirname(__file__))
    pre_path = os.path.abspath(os.path.join(now_path, '..'))
    cache_path = pre_path + "/cache_file"

    #获取文件夹中的所有缓存文件的名称
    dir_cache_file_names = os.listdir(cache_path)

    #过滤掉后缀名
    for i in range(len(dir_cache_file_names)):
        index = dir_cache_file_names[i].find('.pkl')

        #如果找到此后缀名，那么就去掉这个后缀名
        if index != -1:
            dir_cache_file_names[i] = dir_cache_file_names[i][:index]

        #如果没有找到这个后缀名，那么就删除掉这个文件名
        else:
            dir_cache_file_names.remove(i)

    #获取所有加载表中存在的缓存文件的名称
    load_cache_file_names = getLoadCacheName()

    #与加载表中缓存文件名进行比较，相同的文件名进行删除
    for load_cache_file in load_cache_file_names:
        dir_cache_file_names.remove(load_cache_file)

    #删除缓存文件夹中的对应缓存文件
    for dir_cache_file_name in dir_cache_file_names:
        removePkl(dir_cache_file_name)

    return {
        'code': 200,
        'msg': '清除缓存成功',
    }

def getLoadCacheName():
    sheets = get_sheets()

    cache_names = []
    for sheet in sheets:
        if 'md5' in sheet.keys() and sheet['md5'] is not None:
            cache_names.append(sheet['md5'])

        if 'filter_md5' in sheet.keys() and sheet['filter_md5'] is not None:
            cache_names.append(sheet['filter_md5'])

    return cache_names
